package com.pair.micro.common.utils;

import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

import java.io.IOException;
import java.util.Map;

@Configuration
@PropertySource("classpath:/ERROR_INFO.properties")
public class ResponseUtils implements EnvironmentAware {

    @Autowired
    private static Environment env;

    @Override
    public void setEnvironment(Environment environment) {
        env=environment;
    }

    private static final Logger logger = LoggerFactory
            .getLogger(ResponseUtils.class);

    /**
     * 发送json
     */
    public static void renderJsonObject(HttpServletResponse response, Object obj){
        String text = "";
        try {
            text = JacksonUtil.getObjectMapper().writeValueAsString(obj);
        } catch (IOException e) {
            logger.error("系统出错：", e);
        }
        renderJson(response, text);
    }

    public static void renderJsonObject(HttpServletResponse response, Map map, Integer errCode){
        map.put("errCode", errCode);
        map.put("errMsg", env.getProperty(errCode.toString()));
        String text = "";
        try {
            text = JacksonUtil.getObjectMapper().writeValueAsString(map);
        } catch (IOException e) {
            logger.error("系统出错：", e);
        }
        renderJson(response, text);
    }

    /**
     * 发送json。使用UTF-8编码。
     *
     * @param response
     *            HttpServletResponse
     * @param text
     *            发送的字符串
     */
    public static void renderJson(HttpServletResponse response, String text) {
        render(response, "application/json;charset=UTF-8", text);
    }

    /**   a
     * 发送内容。使用UTF-8编码。
     *
     * @param response
     * @param contentType
     * @param text
     */
    public static void render(HttpServletResponse response, String contentType,
                              String text) {
        response.setContentType(contentType);
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        try {
            response.getWriter().write(text);
        } catch (IOException e) {
        }
    }
}
